//내장 모듈, 외장 모듈
var http = require('http');
var express = require('express');
var ejs = require('ejs');
var fs = require('fs');
var mongojs = require('mongojs');

var url = require('url');
var querystring = require('querystring');

//db 연동
var db = mongojs.connect('nodetest', ['nfctest']);
var tdb = mongojs.connect('nodetest', ['tag']);

var app = express();

app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());

app.use(app.router);

/****************************/
/*		app 분기 시작		*/
/****************************/

/* write 페이지(from write.html) */
app.get('/write', function(req, res){
	res.redirect('/write.html');
});

/* write 페이지에서 태그 작성 후 /write_ok 요청(from write.html) */
app.get('/write_ok', function(req, res){
	var parsed = url.parse(req.url);
//	console.log(parsed);
	
	var hash = (new Date()).getTime();
	
	//NFC 저장
	tdb.tag.save({pid:hash, qs:parsed.query});
	db.nfctest.save({pid:hash, memo:'실제 Web DB에는 pid만 저장', qs:parsed.query});
	res.redirect('/view?i=' + hash + '&' + parsed.query);
});

/* 입력 내용 확인 페이지(from log.ejs) */
app.get('/view', function(req, res){
	var pid = req.param('i');
	var owner= req.param('o');
	var name = req.param('n');
	var tel = req.param('t');
	var memo = req.param('m');
	var cash = req.param('c');
	
	var dbData = {pid:pid, owner:owner, name:name,
			tel:tel, memo:memo, cash:cash, sos:null};
	
	fs.readFile(__dirname + '/template/view.ejs', 'utf-8', function(err, ejsData){
		var html = ejs.render(ejsData, {data:dbData});
		res.send(html);
	});
});

/*이미지 & 텍스트 입출력*/
app.post('/upload', function(req, res){
	fs.readFile(req.files.uploadImg.path, function(error, data){
		var pid = req.param("param0");
		var owner = req.param("param1");
		var name = req.param("param2");
		var tel = req.param("param3");
		var memo = req.param("param4");
		var cash = req.param("param5");
		var mt = req.param("param6");
		var mp = req.param("param7");
		var ms = req.param("param8");
		var filePath = __dirname + "\\public\\files\\" + req.files.uploadImg.name + ".jpg";
		
		console.log(pid + ", " + owner + ", " + name + ", " + tel + ", " + memo + ", " + cash + ", " + mt + ", " + mt + ", " + ms + ", " + filePath);
		
		db.nfctest.save({pid:pid, owner:owner, name:name, tel:tel, memo:memo, cash:cash, mt:mt, mp:mp, ms:ms});
		fs.writeFile(filePath, data, function(error){
			if(error){
				throw error;
			}else{
				res.redirect("back");
			}
		});
	});
});

/* TAG 읽기 확인 페이지 - 실종 전단 페이지(from read.html) */
app.get('/read', function(req, res){
	tdb.tag.find(function(err, dbData){
		fs.readFile(__dirname + '/template/readTag.ejs', 'utf-8', function(err, ejsData){
			var html = ejs.render(ejsData, {data : dbData});
			res.send(html);
		});
	});
});

/* readView(from readTag.ejs, readList.ejs, sosList.ejs) */
app.get('/readView', function(req, res){
	db.nfctest.find({pid:req.param('i')},function(err,dbData){
		/*console.log(req.param('i'));
		console.log(dbData[0].pid);*/
		fs.readFile(__dirname + '/template/flyer.ejs', 'utf-8', function(err,ejsData){
			var html = ejs.render(ejsData, {data:dbData[0]});
			res.send(html);
		});
	});
});

/* */
app.get('/readlist', function(req, res){
	tdb.tag.find(function(err,dbData){
		fs.readFile(__dirname + '/template/readList.ejs', 'utf-8', function(err,ejsData){
			var html = ejs.render(ejsData, {data:dbData});
			res.send(html);
		});
	});
});

/* edit(from view.ejs) */
app.post('/edit', function(req, res){
	var pid = req.param('i');
	var owner = req.param('o');
	var name = req.param('n');
	var tel = req.param('t');
	var memo = req.param('m');
	var cash = req.param('c');
	var sos = req.param('s');
	
//	db.nfctest.find({pid:pid});
	db.nfctest.save({pid:pid, owner:owner, name:name,
		tel:tel, memo:memo, cash:cash, sos:sos});

	res.redirect('/log');
});

/* (from index.html) */
app.get('/soslist', function(req, res){
	db.nfctest.find("",function(err,dbData){
		fs.readFile(__dirname + '/template/soslist.ejs', 'utf-8', function(err,ejsData){
			var html = ejs.render(ejsData, {data:dbData});
			res.send(html);
		});
	});
});

/* (log.ejs) */
app.get('/log', function(req, res){
	db.nfctest.find(function(err, dbData){
		fs.readFile(__dirname + '/template/log.ejs', 'utf-8', function(err, ejsData){
			var html = ejs.render(ejsData, { data : dbData });
			res.send(html);
		});
	});
});

/* (from log.ejs) */
app.get('/log/del', function(req, res){
	var pid = req.param('i');
	db.nfctest.remove({ pid : pid }, { justOne : true });
	res.redirect('/log');
});

/* 미구현 (from read.ejs) */
app.get('/log/deltag', function(req, res){
	var pid = req.param('i');
	tdb.tag.remove({ pid : pid });
	res.redirect('/');
});

/* 미구현 (from log.ejs)*/
app.get('/log/clear', function(req, res){
	db.nfctest.remove();
	res.redirect('/log');
});

/****************************/
/*		app 분기 끝			*/
/****************************/

var server = http.createServer(app);
server.listen(8888, function(){
	console.log('S-Pet Server is running!!!');
});
